package de.zainodis.triplog.ui.task;

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import java.util.Date;

import de.zainodis.triplog.data.DataProvider;
import de.zainodis.triplog.data.DiaryEntry;
import de.zainodis.triplog.util.DateTimeUtils;

/**
 * Saves a trip that it takes from the DataProvider.
 */
public class SaveNoteService extends IntentService {

    private static final String TAG = "SaveNoteService";

    public static String ACTION_SAVE_NOTE_SERVICE = "SaveNoteService";
    public static String BUNDLE_TEXT = "Text";

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public SaveNoteService(String name) {
        super(name);
    }

    public SaveNoteService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String text = intent.getStringExtra(BUNDLE_TEXT);
        if (text == null || text.isEmpty()) {
            //Nothing left to do, we're done
            return;
        }
        DiaryEntry note = new DiaryEntry();
        note.setDate(DateTimeUtils.toDbDateString(new Date()));
        note.setText(text);
        DataProvider.addNote(note);

        //Persist changes
        DataProvider.getCurrentTrip().createOrUpdate(this);

        //Send broadcast to notify of change
        Log.i(TAG, "has completed, sending broadcast to notify subscribers.");
        intent = new Intent(ACTION_SAVE_NOTE_SERVICE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}
